<template>
  <Condition 
    :conditionList="conditionList" 
    v-model="condition"
    @change="handleConditionChange"
    @update-teachaerResults="handleResults"
    @clear-teachaerSearch="clearSearchResults"
  />
  <TaskContainer>
    <el-table :data="isSearching ? searchResults : list" style="width: 100%" border ref="tb" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :selectable="isTaskSelectable"/>
      <el-table-column prop="completed" label="难易程度" width="100"/>
      <el-table-column prop="title" label="任务名" class-name="hidden-column">
        <template #default="scope">
          <span style="color:#409EFF;cursor:pointer;" @click="handlePreviewTask(scope.row)">{{scope.row.title}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="detail" label="具体任务" class-name="hidden-column"/>
    </el-table>
    <div style="margin: 20px 0; display: flex; justify-content: flex-end; align-items: center;">
      <!-- <el-button type="primary" @click="assignTasksToGroup">分配到本组</el-button> -->
      <el-pagination background layout="prev, pager, next"
        hide-on-single-page
        :page-size="pagination.rows"
        :pager-count="5"
        v-model:current-page="pagination.page"
        :total="pageTotal"
        @current-change="handlePageChange"
      />
    </div>
  </TaskContainer>
  <el-dialog v-model="showPreviewDialog" title="任务预览" width="60%" :modal="false">
    <div v-if="showPreviewDialog && currentPreviewTask">
      <div><b>任务名：</b>{{ currentPreviewTask.title }}</div>
      <div style="margin:8px 0;"><b>难易程度：</b>{{ currentPreviewTask.completed }}</div>
      <div><b>具体任务：</b>{{ currentPreviewTask.detail }}</div>
    </div>
  </el-dialog>
</template>

<script>
import HeaderNav from "@/components/HeaderNav.vue"
import TaskContainer from "@/components/TaskContainer.vue"
import Condition from "@/components/Condition.vue"
import API from '@/api/index.js'

export default {
  components: {
    HeaderNav,
    TaskContainer,
    Condition,
  },
  props: {
    groupId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      pagination: {
        page: 1,
        rows: 8,
      },
      pageTotal: 0,
      list: [],
      condition: {}, // 查询条件
      searchResults: [], // 存储搜索结果
      isSearching: false, // 是否处于搜索状态
      selectedTasks: [], // 选中的任务
      selectAllUserTask: [], // 存储选取相同任务的Id
      disabledTaskIds: [], // 存储不可选的任务id
      conditionList: [
        {
          name: "编程语言",
          value: 'langName',
          list: [],
          multi: true,
        },
        {
          name: "难易程度",
          value: 'leave',
          list: [
            {id: "简单题", name: "简单题"},
            {id: "中等题", name: "中等题"},
            {id: "难题", name: "难题"},
            {id: "选做题", name: "选做题"},
          ],
          multi: true,
        }
      ],
      showPreviewDialog: false,
      currentPreviewTask: null,
    }
  },
  created(){
    this.queryTasklist()
    this.handleLanagesAndModules()
  },
  methods: {
    queryTasklist(){
      // 查询所有用户数据
      if(this.isSearching) return;
      const params = {
        ...this.condition,
        page: this.pagination.page,
        rows: this.pagination.rows
      }
      API.getTeacherList(params)
      .then(ret=>{
        this.list = ret.data;
        this.pageTotal = ret.total;
      })
    },
    handleLanagesAndModules(){
      API.get_condition_list()
      .then(res=>{
        this.conditionList[0].list = res.data;
      })
    },
    handleConditionChange() {
      this.pagination.page = 1;
      this.queryTasklist();
    },
    handlePageChange(page){
      this.pagination.page = page;
      this.queryTasklist();
    },
    handleResults(results) {
      this.searchResults = results;
      this.isSearching = true;
      this.pagination.page = 1;
      this.pageTotal = results.length;
    },
    clearSearchResults(){
      this.isSearching = false;
      this.searchResults = [];
      this.queryTasklist();
    },
    handleSelectionChange(selection) {
      this.selectedTasks = selection;
    },
    selectUserTask() {
      // 获取每个组的人员的所有的相同任务ID
      API.selectAllUserTask({group_id: this.groupId})
      .then(res=>{
        this.selectAllUserTask = res.data;
        this.disabledTaskIds = res.data || [];
        // 默认勾选这些任务
        this.$nextTick(() => {
          const table = this.$refs.tb;
          if (table) {
            (this.isSearching ? this.searchResults : this.list).forEach(row => {
              if (this.disabledTaskIds.includes(row.id)) {
                table.toggleRowSelection(row, true);
              }
            });
          }
        });
      })
    },
    isTaskSelectable(row) {
      // 返回false则该行不可选
      return !this.disabledTaskIds.includes(row.id);
    },
    async handleAssignTasks() {
      if (!this.selectedTasks.length) {
        this.$message.warning('请先选择要分配的任务');
        return;
      }
      // 获取本组所有用户id
      let userIds = [];
      try {
        const res = await API.getAssignedGroup({ group_id: this.groupId });
        // console.log(res)
        userIds = res.data.map(u => u.id);
        // console.log("组id",this.groupId, "用户IDs", userIds)
      } catch (e) {
        this.$message.error('获取组员失败');
        return;
      }
      const taskIds = this.selectedTasks.map(item => item.id);
      // console.log(taskIds)
      try {
        console.log(taskIds, userIds)
        await API.assignTasksToGroup({ task_ids: taskIds, user_ids: userIds });
        this.$message.success('分配成功');
        this.queryTasklist();
      } catch (e) {
        this.$message.error('分配失败');
      }
    },
    handlePreviewTask(row) {
      this.currentPreviewTask = row;
      this.showPreviewDialog = true;
    },
  },
  watch: {
    'condition.search'(newVal) {
      if (!newVal) {
        this.clearSearchResults();
      }
    }
  }
}
</script>

<style scoped>

:deep(.nav-condition-ul a) {
  color: #333;
}

.table-modules {
  padding: 10px 20px;
}

.table-modules span {
  padding: 2px 10px;
  margin: 0 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.toolbar {
  position: relative;
  right: 10px;
  z-index: 200;
  text-align: right;
  margin: 20px;
  flex: 1 1 auto;
}

:deep(.hidden-column .cell) {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}


</style>
